<template>
 

  <el-container>
    <el-aside width="350px">
      <el-card class="box-card">
        <div  class="text item" style=" display: flex; justify-content: end;">
          <el-button size="mini" type="text" @click="initGeojson">运行</el-button>
        </div>
        <div  class="text item">
          <el-input
            placeholder="geojson请求路径"
            v-model="geojsonPath"
            clearable>
          </el-input>
        </div>
        <div class="text item" style="margin-top: 10px;">
          <el-input
            type="textarea"
            :rows="5"
            placeholder="geojson对象或者字符串"
            v-model="oldGeosjon">
          </el-input>
        </div>
      </el-card>
      <json-viewer style="margin-top: 10px;"
      :value="jsonData"
      :expand-depth=5
      copyable
      boxed
      @copied="onCopy"
      sort/>
    </el-aside>
    <el-main>
      <div class="mapbox-maps">
        <div id="map">      
        </div> 
      </div>   
    </el-main>
  </el-container>  
</template>
<script>
export default{
    name:'MapboxClustered',
    data(){
      return{
        pbfData_1_10: {
          type:'vector',
          tiles:['http://localhost:8081/geoms/get/a_5_10/{z}/{x}/{y}.pbf'],
          minzoom:1,
          maxzoom:10 
        },
        pbfData_1_103: {
          type:'vector',
          tiles:['http://localhost:8081/geoms/get/a_03/{z}/{x}/{y}.pbf'],
          minzoom:1,
          maxzoom:10 
        },
        oldGeosjon:'',
        geojsonPath: 'https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json',
        drawer: false,
        map:{},
        geojson: {        
          type:'geojson',
          data:{
          "type": "FeatureCollection",
          "features":[]
          }
        },
        jsonData: {},
      
      }
    },
    mounted() {
      this.loadMap()
    },
    beforeDestroy(){
      this.map.remove()

    },
    methods:{
        
      loadMap() {
          // 英文标注转换为中文   
          // mapboxgl.setRTLTextPlugin(
          //   "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js"
          // );
          this.map =  new mapboxgl.Map({
              accessToken: 'pk.eyJ1Ijoienh0d24iLCJhIjoiY2wzanV3bHduMTZwejNrcXcyd3B1bzBieiJ9.aW_TDqLomftwPvBu7OWqwQ',
              container: 'map',
              style: 'mapbox://styles/mapbox/outdoors-v10', // stylesheet location
              center: [116.790202563,32.656293335],  //[116.79507,32.65542], // starting position [lng, lat]
              zoom: 15, // starting zoom
              hash: false,
              //pitch: 45,  //地图的角度，不写默认是0，取值是0-60度，一般在3D中使用
              bearing: 0, //地图的初始方向，值是北的逆时针度数，默认是0，即是正北
              antialias: true, //抗锯齿，通过false关闭提升性能
          })
          // 设置语言
          // var language = new MapboxLanguage({ defaultLanguage: "zh" });
          // this.map.addControl(language);

          //地图导航
          var nav = new mapboxgl.NavigationControl();
          this.map.addControl(nav, 'top-right');

          // 比例尺
          var scale = new mapboxgl.ScaleControl({
              maxWidth: 100,
              unit: "metric"
          });
          this.map.addControl(scale,"bottom-left");

          // 全图
          this.map.addControl(new mapboxgl.FullscreenControl());
          // 定位
          this.map.addControl(
              new mapboxgl.GeolocateControl({
              positionOptions: {
                  enableHighAccuracy: true
              },
              trackUserLocation: true
              })
          );
          let that = this;
          this.map.on('load',function () {
            that.map.addSource("clustered",that.geojson);//点聚合成簇
			that.map.addSource("centroid",that.geojson);//提取簇的中心
            that.map.addSource("voronoi",that.geojson);//使用voronoi算法把 提取簇的中心生成面   
			that.map.addSource("intersection",that.geojson);// 使用ST_Intersection方法切割 用voronoi算法构成的面，去切割原始的jzd边界   
            //点聚合成簇	
            that.map.addLayer({
                id: "clustered",
                type: "circle",
                source: "clustered",
                paint: {
                    "circle-radius": 2,
                    "circle-color": [
						"case",
						["boolean",["==",["get","cluster"],0],false],"#FFFFFF",
						["boolean",["==",["get","cluster"],1],false],"#FFFFCC",
						["boolean",["==",["get","cluster"],2],false],"#45D23E",
						["boolean",["==",["get","cluster"],3],false],"#5D93F5",
						["boolean",["==",["get","cluster"],4],false],"#CCCCCC",
						["boolean",["==",["get","cluster"],5],false],"#F39C19",
						["boolean",["==",["get","cluster"],6],false],"#AAAAAA",
						["boolean",["==",["get","cluster"],7],false],"#FF0088",
						["boolean",["==",["get","cluster"],8],false],"#CC6600",
						["boolean",["==",["get","cluster"],9],false],"#888800",
						["boolean",["==",["get","cluster"],10],false],"#008800",
						["boolean",["==",["get","cluster"],11],false],"#008866",
						["boolean",["==",["get","cluster"],12],false],"#008888",
						["boolean",["==",["get","cluster"],13],false],"#007799",
						["boolean",["==",["get","cluster"],14],false],"#770077",
						["boolean",["==",["get","cluster"],15],false],"#F0BBFF",
						["boolean",["==",["get","cluster"],16],false],"#E43961",
						"black"
					],
                }
            });		
			//提取簇的中心
			that.map.addLayer({
                  id: "centroid",
                  type: "circle",
                  source: "centroid",
                  paint: {
                      "circle-radius": 5,
                      "circle-color": "#00FF00",
                  }
              });
			  
			//使用voronoi算法把 提取簇的中心生成面  
		    that.map.addLayer({
			  'id': 'voronoi_polygon',
			  'type': 'fill',
			  'source': 'voronoi',
			  'paint': {
				  'fill-color': '#FFFF00',
				  'fill-opacity': 0.6
			  },
		    });
			that.map.addLayer({
			    "id": "voronoi_line",
                "type": "line",
                "source": "voronoi",              
                "layout": {
					"visibility": "visible",			
				},
                "paint": {
				    "line-opacity": 1,
					"line-color": "#000000",
					"line-width": 1,				
                 } 
            })	


            // 使用ST_Intersection方法切割 用voronoi算法构成的面，去切割原始的jzd边界  
		    that.map.addLayer({
			  'id': 'intersection_polygon',
			  'type': 'fill',
			  'source': 'intersection',
			  'paint': {
				  'fill-color': '#CC6600',
				  'fill-opacity': 0.1
			  },
		    });
			that.map.addLayer({
			    "id": "intersection_line",
                "type": "line",
                "source": "intersection",              
                "layout": {
					"visibility": "visible",			
				},
                "paint": {
				    "line-opacity": 1,
					"line-color": "#33FFFF",
					"line-width": 1,				
                 } 
            })							
			

            //that.loadGeojson()
			
			//加载点聚合成簇
			that.loadClustered();
			//提取簇的中心
			that.loadCentroid();
			//使用voronoi算法把 提取簇的中心生成面
			//that.loadVoronoi();
			// 使用ST_Intersection方法切割 用voronoi算法构成的面，去切割原始的jzd边界
			that.loadIntersection()
              
          })
          
      },
      /**
       * 拷贝geojson
       */
      onCopy(e){
          console.log(e)
          alert(e)
      },	
	  /*
	  * 点聚合成簇
	  */
	  loadClustered(){
	    debugger
        let that = this
        let url = "/analysis/clustered"
		  that.$axios({
			url: url,
			method: 'post',
			data:{},
		  })
		  .then(function (res) {          
		   console.log(res)
		   let features = []
		   res.data.data.forEach(e=>{
			let geom = JSON.parse(e.row_to_json.value)    
			features=geom.features			
			//features.push({
			// "type": "Feature",
			//  "geometry":geom,
			//  "properties": {"status": "status"}
			//})
		   })
		   that.map.getSource('clustered').setData({
			  "type": "FeatureCollection",
			  "features":[]
			})
		  that.map.getSource('clustered').setData({
		  "type": "FeatureCollection",
		  "features":features
		  })
		  })
		  .catch(function (error) {
			// handle error
			console.log(error);
		  })   
	  
	  },
	  loadCentroid(){	  
        let that = this
        let url = "/analysis/centroid"
		  that.$axios({
			url: url,
			method: 'post',
			data:{},
		  })
		  .then(function (res) {          
		   console.log(res)
		   let features = []
		   res.data.data.forEach(e=>{
			let geom = JSON.parse(e.row_to_json.value)    
			features=geom.features			
			//features.push({
			// "type": "Feature",
			//  "geometry":geom,
			//  "properties": {"status": "status"}
			//})
		   })
		   that.map.getSource('centroid').setData({
			  "type": "FeatureCollection",
			  "features":[]
			})
		  that.map.getSource('centroid').setData({
		  "type": "FeatureCollection",
		  "features":features
		  })
		  })
		  .catch(function (error) {
			// handle error
			console.log(error);
		  })   
	  
	  },
	  loadVoronoi(){	    
        let that = this
        let url = "/analysis/voronoi"
		  that.$axios({
			url: url,
			method: 'post',
			data:{},
		  })
		  .then(function (res) {          
		   console.log(res)
		   let features = []
		   res.data.data.forEach(e=>{
			let geom = JSON.parse(e.row_to_json.value)    
			features=geom.features			
			//features.push({
			// "type": "Feature",
			//  "geometry":geom,
			//  "properties": {"status": "status"}
			//})
		   })
		   that.map.getSource('voronoi').setData({
			  "type": "FeatureCollection",
			  "features":[]
			})
		  that.map.getSource('voronoi').setData({
		  "type": "FeatureCollection",
		  "features":features
		  })
		  })
		  .catch(function (error) {
			// handle error
			console.log(error);
		  })   
	  },
	  loadIntersection(){
	    debugger
        let that = this
        let url = "/analysis/intersection"
		  that.$axios({
			url: url,
			method: 'post',
			data:{},
		  })
		  .then(function (res) {          
		   console.log(res)
		   let features = []
		   res.data.data.forEach(e=>{
			let geom = JSON.parse(e.row_to_json.value)    
			features=geom.features			
			//features.push({
			// "type": "Feature",
			//  "geometry":geom,
			//  "properties": {"status": "status"}
			//})
		   })
		   that.map.getSource('intersection').setData({
			  "type": "FeatureCollection",
			  "features":[]
			})
		  that.map.getSource('intersection').setData({
		  "type": "FeatureCollection",
		  "features":features
		  })
		  })
		  .catch(function (error) {
			// handle error
			console.log(error);
		  })  
	  
	  },
      loadGeojson(){
        debugger
        let that = this
        let url = "/analysis/square"
         // that.$axios({
         //   url: url,
         //   method: 'post',
         //   data:{},
         // })
        //  .then(function (res) {          
        //   console.log(res)
        //   let features = []
        //   res.data.data.forEach(e=>{
        //    let geom = JSON.parse(e.geom)    
        //    features.push(geom)			
        //    //features.push({
            // "type": "Feature",
            //  "geometry":geom,
            //  "properties": {"status": "status"}
            //})
        //   })
        //   that.map.getSource('gps-points').setData({
        //      "type": "FeatureCollection",
        //      "features":[]
         //   })
        //  that.map.getSource('gps-points').setData({
         // "type": "FeatureCollection",
        //  "features":features
        //  })
        //  })
        //  .catch(function (error) {
            // handle error
        //    console.log(error);
        //  })   
		  
		  that.$axios({
            url: "/analysis/geojson",
            method: 'post',
            data:{},
          })
          .then(function (res) {          
           console.log(res)
           let features = []
           res.data.data.forEach(e=>{
            let geom = JSON.parse(e.geom)    
            //features.push(geom)			
            features.push({
             "type": "Feature",
             "geometry":geom,
             "properties": {"status": "status"}
            })
           })
           that.map.getSource('gps-pointss').setData({
              "type": "FeatureCollection",
              "features":[]
            })
          that.map.getSource('gps-pointss').setData({
			  "type": "FeatureCollection",
			  "features":features
          })
          })
          .catch(function (error) {
            // handle error
            console.log(error);
          })   

      },
      /**
       * 渲染geojson数据
       * 
       */
      initGeojson(){
        let that = this
        let ISNULL =false;
        if(that.geojsonPath!=""){
          ISNULL = true
        }
        console.log(that)
        if(ISNULL){
          that.map.getSource('national-park').setData({
            "type": "FeatureCollection",
            "features":[]
          })
          that.map.getSource('national-park').setData(that.geojsonPath)
          let urls = that.geojsonPath.split("https://geo.datav.aliyun.com")
          that.$axios({
            url: urls[1],
            method: 'get',
            data:{},
          })
          .then(function (res) {          
            that.jsonData = res.data
            that.map.flyTo({
              center:res.data.features[0].properties.center,
              zoom: 4,
              bearing: 0,
              speed: 0.8, // make the flying slow
              curve: 1, // change the speed at which it zooms out
            });
            console.log(res);
          })
          .catch(function (error) {
            // handle error
            console.log(error);
          })   
        }else{
          debugger
          if(that.oldGeosjon == "" || that.oldGeosjon ==  {}){
            that.jsonData = {}
            that.map.getSource('national-park').setData({
              "type": "FeatureCollection",
              "features":[]
            })
          }
          if(typeof(that.oldGeosjon) == "string"){
            that.jsonData = JSON.parse(that.oldGeosjon)
            that.map.getSource('national-park').setData({
              "type": "FeatureCollection",
              "features":[]
            })
            that.map.getSource('national-park').setData(that.jsonData)
            that.map.flyTo({
              center:that.jsonData.features[0].properties.center,
              zoom: 4,
              bearing: 0,
              speed: 0.8, // make the flying slow
              curve: 1, // change the speed at which it zooms out
            });
          }
          if(Object.prototype.toString.call(that.oldGeosjon) === '[object Object]'){
            that.jsonData = that.oldGeosjon
            that.map.getSource('national-park').setData({
              "type": "FeatureCollection",
              "features":[]
            })
            that.map.getSource('national-park').setData(that.jsonData)
             that.map.flyTo({
              center:that.jsonData.features[0].properties.center,
              zoom: 4,
              bearing: 0,
              speed: 0.8, // make the flying slow
              curve: 1, // change the speed at which it zooms out
            });
          }
          
        }       
      }
    }
}

</script>
<style scoped lang="scss">
 @import "../../../public/mapbox/mapbox-gl.css";
 .mapbox-maps {
    width: 100%;
    height: calc(100vh - 50px);
    position: relative;
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        bottom:0;
        right: 0;        
    }
    
}
.mapboxgl-canvas {
    outline: none;
}
  /* 隐藏mapbox商标 */
.mapboxgl-ctrl-logo {
    display: none;
} 
.el-aside {
    overflow: auto;
    box-sizing: border-box;
    flex-shrink: 0;
    width: 200px;
    // border: 1px solid red;
    line-height: 19px;
    padding: 10px;
    text-align: left;
}
.jv-container .jv-code.boxed {
    max-height: 100%;
}
</style>